package com.ufo.store.management.ui.fragment;

import android.app.Activity;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.text.Editable;
import android.text.InputType;
import android.text.method.DigitsKeyListener;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.ufo.store.management.BarApplication;
import com.ufo.store.management.R;
import com.ufo.store.management.database.DatabaseManager;
import com.ufo.store.management.entity.SerializableMap;
import com.ufo.store.management.entity.StockInfo;
import com.ufo.store.management.utils.Utils;
import com.ufo.store.management.widget.view.FloatTextToast;

import com.ufo.store.management.widget.dialog.ProtogenesisInputDialog;
import com.ufo.store.management.widget.dialog.TipsDialog;
import com.ufo.store.management.widget.zxing.MipcaActivityCapture;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by taoli on 2016/5/17.
 */
public class StockEditFragment extends Fragment {
    private final int ACTIVITY_RESULT_BRANDECODE = 1;

    private LinearLayout mRootLayout;
    private EditText mStockIdEt = null;
    private EditText mStockNameEt = null;
    private EditText mStockSpellEt = null;
    private EditText mStockUnitEt = null;
    private EditText mStockTypeidEt = null;
    private EditText mStockCostEt = null;
    private EditText mStockRetailPriceEt = null;
    private EditText mStockMemberPriceEt = null;
    private ImageView mAddBrandcodeIv = null;
    private ImageView mRemoveBrandcodeIv = null;
    private HashMap<String, Object> mBrandeCodeMap = new HashMap<String, Object>();
    private EditText mCurrenBrandeCodeEt = null;

    //传入参数
    private StockInfo mStockInfo = null;
    private boolean mbIsInsertData = true;
    private SerializableMap mStockTypeMap = null;
    private long mMaxStockIndex = -1;

    private TipsDialog mTipsDialog = null;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mRootLayout = (LinearLayout) inflater.inflate(R.layout.fragment_stock_edit, container, false);
        mbIsInsertData = getArguments().getBoolean("IsInsertData");
        mMaxStockIndex = getArguments().getLong("MaxStockIndex");
        mStockTypeMap = (SerializableMap) getArguments().getSerializable("StockType");
        mStockInfo = (StockInfo) getArguments().getSerializable("StockInfo");
        //LinearLayout content_ll = (LinearLayout) mRootLayout.findViewById(R.id.content_ll);
        //AnimationUtil.setTopToBottomAnimation(content_ll, 350, 0.1f);
        initialize(mRootLayout);
        initData();
        return mRootLayout;
    }

    private void initialize(View rootView) {
        mStockIdEt = (EditText) rootView.findViewById(R.id.stock_id_et);
        mStockNameEt = (EditText) rootView.findViewById(R.id.stock_name_et);
        mStockSpellEt = (EditText) rootView.findViewById(R.id.stock_spell_et);
        mStockUnitEt = (EditText) rootView.findViewById(R.id.stock_unit_et);
        mStockTypeidEt = (EditText) rootView.findViewById(R.id.stock_typeid_et);
        mStockCostEt = (EditText) rootView.findViewById(R.id.stock_cost_et);
        mStockRetailPriceEt = (EditText) rootView.findViewById(R.id.stock_retail_price_et);
        mStockMemberPriceEt = (EditText) rootView.findViewById(R.id.stock_member_price_et);

        mAddBrandcodeIv = (ImageView) rootView.findViewById(R.id.brandcode_add_iv);
        mRemoveBrandcodeIv = (ImageView) rootView.findViewById(R.id.brandcode_remove_iv);

        mStockNameEt.addTextChangedListener(new android.text.TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                String chineseSpell = Utils.cn2FirstSpell(s.toString());
                mStockSpellEt.setText(chineseSpell);
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });

        mStockRetailPriceEt.addTextChangedListener(new android.text.TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                mStockMemberPriceEt.setText(s);
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });

        insetOneBrandeCodeLayout();

        if (mStockInfo != null) {
            mStockIdEt.setText(mStockInfo.stockId);
            mStockNameEt.setText(mStockInfo.stockName);
            mStockSpellEt.setText(mStockInfo.stockSpell);
            mStockUnitEt.setText(mStockInfo.stockUnit);
            mStockTypeidEt.setText(mStockTypeMap.getMap().get(mStockInfo.stockTpyeId).trim());
            mCurrenBrandeCodeEt = (EditText) mBrandeCodeMap.get("1");
            mCurrenBrandeCodeEt.setText(mStockInfo.stockBarcode);
            mStockCostEt.setText(String.valueOf(mStockInfo.stockCost));
            mStockRetailPriceEt.setText(String.valueOf(mStockInfo.stockDetailPrice));
            mStockMemberPriceEt.setText(String.valueOf(mStockInfo.stockMemberPrice));

        }
        if (BarApplication.getInstance().mbStockDisplayCost)
            mStockCostEt.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
        else
            mStockCostEt.setTransformationMethod(PasswordTransformationMethod.getInstance());

        if (mbIsInsertData) {
            new GetStockMaxIndexTask().execute();
        } else {
            mAddBrandcodeIv.setVisibility(View.GONE);
            mRemoveBrandcodeIv.setVisibility(View.GONE);
        }
    }

    private void initData() {

    }

    public void onClick(View v) {
        switch (v.getId()){
            case R.id.rl1:
            case R.id.stock_id_et:
                new ProtogenesisInputDialog(getActivity(), mStockIdEt, "商品序号", new DigitsKeyListener(false, false)).setItemClickListener(new ProtogenesisInputDialog.OnItemClick() {
                    @Override
                    public void onPositiveButtonClick(String inputString) {
                        mStockIdEt.setText(inputString);
                    }

                    @Override
                    public void onNegativeButtonClick() {

                    }
                });
                break;
            case R.id.rl2:
            case R.id.stock_name_et:
                new ProtogenesisInputDialog(getActivity(), mStockNameEt, "商品名称", null).setItemClickListener(new ProtogenesisInputDialog.OnItemClick() {
                    @Override
                    public void onPositiveButtonClick(String inputString) {
                        mStockNameEt.setText(inputString);
                    }

                    @Override
                    public void onNegativeButtonClick() {

                    }
                });
                break;
            case R.id.rl3:
            case R.id.stock_spell_et:
                new ProtogenesisInputDialog(getActivity(), mStockSpellEt, "名称拼音首字母缩写", null).setItemClickListener(new ProtogenesisInputDialog.OnItemClick() {
                    @Override
                    public void onPositiveButtonClick(String inputString) {
                        mStockSpellEt.setText(inputString);
                    }

                    @Override
                    public void onNegativeButtonClick() {

                    }
                });
                break;
            case R.id.rl4:
            case R.id.stock_unit_et:
                AlertDialog alertDialog = new AlertDialog.Builder(getActivity()).setTitle("单价计量单位")
                        .setMessage("不可更改")
                        .setPositiveButton("知道了", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                            }
                        }).create();
                alertDialog.getWindow().setWindowAnimations(R.style.dialog_anim_center_style);
                alertDialog.show();
                break;
            case R.id.rl5:
            case R.id.stock_typeid_et:
                showStockTypeList();
                break;
            case R.id.rl7:
            case R.id.stock_cost_et:
                new ProtogenesisInputDialog(getActivity(), mStockCostEt, "商品的进货价格", new DigitsKeyListener(false, true)).setItemClickListener(new ProtogenesisInputDialog.OnItemClick() {
                    @Override
                    public void onPositiveButtonClick(String inputString) {
                        mStockCostEt.setText(inputString);
                    }

                    @Override
                    public void onNegativeButtonClick() {

                    }
                });
                break;
            case R.id.rl8:
            case R.id.stock_retail_price_et:
                new ProtogenesisInputDialog(getActivity(), mStockRetailPriceEt, "商品的零售价格", new DigitsKeyListener(false, true)).setItemClickListener(new ProtogenesisInputDialog.OnItemClick() {
                    @Override
                    public void onPositiveButtonClick(String inputString) {
                        mStockRetailPriceEt.setText(inputString);
                    }

                    @Override
                    public void onNegativeButtonClick() {

                    }
                });
                break;
            case R.id.rl9:
            case R.id.stock_member_price_et:
                new ProtogenesisInputDialog(getActivity(), mStockMemberPriceEt, "商品的会员价格", new DigitsKeyListener(false, true)).setItemClickListener(new ProtogenesisInputDialog.OnItemClick() {
                    @Override
                    public void onPositiveButtonClick(String inputString) {
                        mStockMemberPriceEt.setText(inputString);
                    }

                    @Override
                    public void onNegativeButtonClick() {

                    }
                });
                break;
            case R.id.brandcode_add_iv:
                insetOneBrandeCodeLayout();
                break;
            case R.id.brandcode_remove_iv:
                removeOneBrandeCodeLayout();
                break;
        }
    }

    /**
     * @desc 商品所属分类选择
     * @author taoli
     * @time 2017/8/31 0031
     */
    private void showStockTypeList() {
        Map<String, String> map = this.mStockTypeMap.getMap();
        //有一个“全部”的分类需去除
        final String[] strKey = new String[map.size()-1];
        final String[] strValue = new String[map.size()-1];
        int len = 0;
        for (String key : map.keySet()) {
            if(!key.equals("-1")) {
                strKey[len] = key;
                strValue[len] = map.get(key);
                len++;
            }
        }

        AlertDialog alertDialog = new AlertDialog.Builder(getActivity()).setTitle("商品种类选择").setItems(strValue, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                mStockInfo.stockTpyeId = strKey[which];
                mStockTypeidEt.setText(strValue[which].trim());
            }
        }).create();
        alertDialog.getWindow().setWindowAnimations(R.style.dialog_anim_center_style);
        alertDialog.show();
    }

    private void insetOneBrandeCodeLayout() {
        LinearLayout stockBrandeLl = (LinearLayout) mRootLayout.findViewById(R.id.rl6);
        LinearLayout.LayoutParams LP_FW = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        LP_FW.topMargin = (int) Utils.dp2px(getResources(), 0);

        LinearLayout layout_sub_Lin = new LinearLayout(getActivity());
        layout_sub_Lin.setTag(String.valueOf(mBrandeCodeMap.size() + 1 + 100));
        layout_sub_Lin.setOrientation(LinearLayout.HORIZONTAL);

        LinearLayout.LayoutParams LP_WW_ET = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        LP_WW_ET.weight = 1.0f;
        LP_WW_ET.height = (int) Utils.dp2px(getResources(), 40);
        String hint = "包装上的条码";
        final EditText ev = new EditText(getActivity());
        ev.setPadding((int) Utils.dp2px(getResources(), 0), 0, 0, 0);
        ev.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14);
        ev.setTextColor(0xff5c5c5c);
        ev.setHint(hint.subSequence(0, hint.length()));
        ev.setSingleLine(true);
        ev.setRawInputType(InputType.TYPE_CLASS_NUMBER);
        ev.setImeOptions(EditorInfo.IME_ACTION_DONE);
        ev.setGravity(Gravity.CENTER_VERTICAL);
        //ev.setBackground(getResources().getDrawable(R.drawable.edit_red_select));
        ev.setBackground(null);
        ev.setTag(String.valueOf(mBrandeCodeMap.size() + 1));
        ev.setClickable(true);
        ev.setCursorVisible(false);
        ev.setFocusable(false);
        ev.setFocusableInTouchMode(false);
        ev.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                new ProtogenesisInputDialog(getActivity(), ev, "商品条码", new DigitsKeyListener(false, false)).setItemClickListener(new ProtogenesisInputDialog.OnItemClick() {
                    @Override
                    public void onPositiveButtonClick(String inputString) {
                        ev.setText(inputString);
                    }

                    @Override
                    public void onNegativeButtonClick() {

                    }
                });
            }
        });
        ev.setLayoutParams(LP_WW_ET);
        layout_sub_Lin.addView(ev);

        LinearLayout.LayoutParams LP_WW_BT = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        LP_WW_BT.height = (int) Utils.dp2px(getResources(), 40);
        LP_WW_BT.width = (int) Utils.dp2px(getResources(), 40);
//        Button bt = new Button(getActivity());
//        bt.setText("选择");
//        bt.setTextAppearance(getActivity(), R.style.button_style);
//        bt.setBackgroundResource(R.drawable.button_background_selector);
//        bt.setTag(String.valueOf(10 + mBrandeCodeMap.size() + 1));
//        bt.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                String vv = String.valueOf(Integer.parseInt(v.getTag().toString()) - 10);
//                mCurrenBrandeCodeEt = (EditText) mBrandeCodeMap.get(vv);
//                Intent intent = new Intent();
//                intent.setClass(getActivity(), MipcaActivityCapture.class);
//                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//                startActivityForResult(intent, ACTIVITY_RESULT_BRANDECODE);
//            }
//        });
//
//        bt.setLayoutParams(LP_WW_BT);
        ImageButton bt = new ImageButton(getActivity());
        bt.setImageResource(R.drawable.ic_next_dark);
        bt.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
        bt.setTag(String.valueOf(10 + mBrandeCodeMap.size() + 1));
        bt.getBackground().setAlpha(0);
        bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String vv = String.valueOf(Integer.parseInt(v.getTag().toString()) - 10);
                mCurrenBrandeCodeEt = (EditText) mBrandeCodeMap.get(vv);
                Intent intent = new Intent();
                intent.setClass(getActivity(), MipcaActivityCapture.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivityForResult(intent, ACTIVITY_RESULT_BRANDECODE);
            }
        });

        bt.setLayoutParams(LP_WW_BT);
        layout_sub_Lin.addView(bt);

        stockBrandeLl.addView(layout_sub_Lin, LP_FW);
        mBrandeCodeMap.put(String.valueOf(mBrandeCodeMap.size() + 1), ev);
    }

    private void removeOneBrandeCodeLayout() {
        if (mBrandeCodeMap.size() > 1) {
            LinearLayout stockBrandeLl = (LinearLayout) mRootLayout.findViewById(R.id.rl6);
            String tag = String.valueOf(mBrandeCodeMap.size() + 100);
            LinearLayout ll = (LinearLayout) stockBrandeLl.findViewWithTag(tag);
            stockBrandeLl.removeView(ll);
            mBrandeCodeMap.remove(String.valueOf(mBrandeCodeMap.size()));
        }
    }

    public void submitStockEdit() {
        String stockIdEtStr = mStockIdEt.getText().toString();
        String stockNameEtStr = mStockNameEt.getText().toString();
        String stockSpellEtStr = mStockSpellEt.getText().toString();
        String stockUnitEtStr = mStockUnitEt.getText().toString();
        String stockCostEtStr = mStockCostEt.getText().toString();
        String stockRetailPriceEtStr = mStockRetailPriceEt.getText().toString();
        String stockMemberPriceEtStr = mStockMemberPriceEt.getText().toString();
        //应该为''字符，不是null
        String stockGroupId = new String();
        //直接赋值为null即可
        String stockPosStr = new String();

        float stockCost;
        float stockRetailPrice;
        float stockMemberPrice;

        if (stockIdEtStr.length() == 0) {
            FloatTextToast.makeText(getActivity(), mStockIdEt, "商品ID不能为空！", FloatTextToast.LENGTH_SHORT).show();
            return;
        }
        if (stockNameEtStr.length() == 0) {
            FloatTextToast.makeText(getActivity(), mStockNameEt, "商品名称不能为空！", FloatTextToast.LENGTH_SHORT).show();
            return;
        }
        if (stockSpellEtStr.length() == 0) {
            FloatTextToast.makeText(getActivity(), mStockSpellEt, "商品名称拼音首字母缩写不能为空！", FloatTextToast.LENGTH_SHORT).show();
            return;
        }

        if (stockUnitEtStr.length() == 0) {
            stockUnitEtStr = "斤";
            mStockUnitEt.setText("斤");
        }
        if (stockCostEtStr.length() == 0) {
            stockCostEtStr = "0";
            mStockCostEt.setText("0");
        }
        if (stockRetailPriceEtStr.length() == 0) {
            stockRetailPriceEtStr = "0";
            mStockRetailPriceEt.setText("0");
        }
        if (stockMemberPriceEtStr.length() == 0) {
            stockMemberPriceEtStr = "0";
            mStockMemberPriceEt.setText("0");
        }

        try {
            stockCost = Float.parseFloat(stockCostEtStr);
        } catch (Exception e) {
            FloatTextToast.makeText(getActivity(), mStockCostEt, "商品进货价格输入错误！", FloatTextToast.LENGTH_SHORT).show();
            return;
        }
        try {
            stockRetailPrice = Float.parseFloat(stockRetailPriceEtStr);
        } catch (Exception e) {
            FloatTextToast.makeText(getActivity(), mStockRetailPriceEt, "商品零售价格输入错误！", FloatTextToast.LENGTH_SHORT).show();
            return;
        }
        try {
            stockMemberPrice = Float.parseFloat(stockMemberPriceEtStr);
        } catch (Exception e) {
            FloatTextToast.makeText(getActivity(), mStockMemberPriceEt, "商品会员价格输入错误！", FloatTextToast.LENGTH_SHORT).show();
            return;
        }

        try {
            ContentValues initialValues = null;
            List<ContentValues> mContentList = new ArrayList<ContentValues>();
            int stockId = -1;
            try {
                stockId = Integer.parseInt(stockIdEtStr.trim());
            } catch (Exception e) {
                FloatTextToast.makeText(getActivity(), mStockIdEt, "商品ID输入错误！", FloatTextToast.LENGTH_SHORT).show();
                return;
            }

            for (Object object : mBrandeCodeMap.values()) {
                EditText et = (EditText) object;
                if (et.getText().toString().length() != 0) {
                    String brande = et.getText().toString();

                    initialValues = new ContentValues();
                    initialValues.put(DatabaseManager.STOCK_STOCKID, String.valueOf(stockId));
                    initialValues.put(DatabaseManager.STOCK_STOCKNAME, stockNameEtStr);
                    initialValues.put(DatabaseManager.STOCK_GROUPID, stockGroupId);
                    initialValues.put(DatabaseManager.STOCK_UNIT, stockUnitEtStr);
                    initialValues.put(DatabaseManager.STOCK_TYPEID, mStockInfo.stockTpyeId);
                    initialValues.put(DatabaseManager.STOCK_COST, stockCost);
                    initialValues.put(DatabaseManager.STOCK_RETAIL_PRICE, stockRetailPrice);
                    initialValues.put(DatabaseManager.STOCK_MEMBER_PRICE, stockMemberPrice);
                    initialValues.put(DatabaseManager.STOCK_WHOLE_PRICE, stockRetailPrice);
                    initialValues.put(DatabaseManager.STOCK_CAN_DISCOUNT, "Y");
                    initialValues.put(DatabaseManager.STOCK_FRONTEDN, "Y");
                    initialValues.put(DatabaseManager.STOCK_PAUSE, "N");
                    initialValues.put(DatabaseManager.STOCK_CLOSEOFF, "N");
                    initialValues.put(DatabaseManager.STOCK_STORABLE, "N");
                    initialValues.put(DatabaseManager.STOCK_STOCKTYPE, "D");
                    initialValues.put(DatabaseManager.STOCK_BARCODE, brande);
                    initialValues.put(DatabaseManager.STOCK_STOCKPOS, stockPosStr);
                    initialValues.put(DatabaseManager.STOCK_SPELL, stockSpellEtStr);
                    initialValues.put(DatabaseManager.STOCK_SUIT_FLAGE, "N");

                    stockId = stockId + 1;

                    mContentList.add(initialValues);
                }
            }
            if (mContentList.size() == 0) {
                initialValues = new ContentValues();
                initialValues.put(DatabaseManager.STOCK_STOCKID, String.valueOf(stockId));
                initialValues.put(DatabaseManager.STOCK_STOCKNAME, stockNameEtStr);
                initialValues.put(DatabaseManager.STOCK_GROUPID, stockGroupId);
                initialValues.put(DatabaseManager.STOCK_UNIT, stockUnitEtStr);
                initialValues.put(DatabaseManager.STOCK_TYPEID, mStockInfo.stockTpyeId);
                initialValues.put(DatabaseManager.STOCK_COST, stockCost);
                initialValues.put(DatabaseManager.STOCK_RETAIL_PRICE, stockRetailPrice);
                initialValues.put(DatabaseManager.STOCK_MEMBER_PRICE, stockMemberPrice);
                initialValues.put(DatabaseManager.STOCK_WHOLE_PRICE, stockRetailPrice);
                initialValues.put(DatabaseManager.STOCK_CAN_DISCOUNT, "Y");
                initialValues.put(DatabaseManager.STOCK_FRONTEDN, "Y");
                initialValues.put(DatabaseManager.STOCK_PAUSE, "N");
                initialValues.put(DatabaseManager.STOCK_CLOSEOFF, "N");
                initialValues.put(DatabaseManager.STOCK_STORABLE, "N");
                initialValues.put(DatabaseManager.STOCK_STOCKTYPE, "D");
                initialValues.put(DatabaseManager.STOCK_BARCODE, "");
                initialValues.put(DatabaseManager.STOCK_STOCKPOS, stockPosStr);
                initialValues.put(DatabaseManager.STOCK_SPELL, stockSpellEtStr);
                initialValues.put(DatabaseManager.STOCK_SUIT_FLAGE, "N");

                mContentList.add(initialValues);
            }

            new SubmitStockInfoTask().execute(mContentList);

        } catch (Exception e) {
            return;
        }
    }

    private class GetStockMaxIndexTask extends AsyncTask<Void, Void, String> {
        public GetStockMaxIndexTask() {
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected String doInBackground(Void... params) {
            if (getActivity().isFinishing()) {
                return "-1";
            }

            String maxIndexStr = null;
            if (BarApplication.getInstance().mDatabaseIsSqlServer) {
                if (mbIsInsertData)
                    maxIndexStr = DatabaseManager.getStockMaxIndexFromSqlServer(getActivity(), mMaxStockIndex);
            }

            return maxIndexStr;
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            if (getActivity().isFinishing()) {
                return;
            }
            if (!result.contains("-1")) {
                mStockIdEt.setText(result);
            }
        }
    }

    private class SubmitStockInfoTask extends AsyncTask<List<ContentValues>, Void, String> {
        public SubmitStockInfoTask() {
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected String doInBackground(List<ContentValues>... params) {
            if (getActivity().isFinishing()) {
                return "";
            }
            List<ContentValues> initialValuesList = params[0];
            long row = -1;
            if (BarApplication.getInstance().mDatabaseIsSqlServer) {
                if (mbIsInsertData) {
                    row = DatabaseManager.insertStockInfoFromSqlServer(getActivity(), initialValuesList);
                } else {
                    row = DatabaseManager.replaceStockInfoFromSqlServer(getActivity(), initialValuesList.get(0));
                }
            }
            return String.valueOf(row);
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            if (getActivity().isFinishing()) {
                return;
            }
            if (result.contains("-1")) {
                if (BarApplication.getInstance().mDatabaseIsSqlServer) {
                    showTipsDialog("对不起，信息修改失败。");
                } else if (mOnProcessListener != null) {
                    mOnProcessListener.onProcessFinish(mStockIdEt.getText().toString());
                }
            } else {
                if (mOnProcessListener != null) {
                    mOnProcessListener.onProcessFinish(mStockIdEt.getText().toString());
                }
                getActivity().setResult(Activity.RESULT_OK);
                showTipsDialog("恭喜，成功修改了" + result + "条数据。");
            }
        }
    }

    public void showTipsDialog(final String tips) {
        if (mTipsDialog == null) {
            mTipsDialog = new TipsDialog(getActivity());
            Window window = mTipsDialog.getWindow(); //得到对话框
            window.setWindowAnimations(R.style.dialog_anim_center_style); //设置窗口弹出动画
        }
        mTipsDialog.setTips(tips);
        mTipsDialog.setItemClickListener(new TipsDialog.OnItemClick() {
            @Override
            public void onItemClick(int position) {
                if (position == 0) {
                }
            }
        });
        mTipsDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
            }
        });
        mTipsDialog.show();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == ACTIVITY_RESULT_BRANDECODE) {
            if (data != null) {
                if (mCurrenBrandeCodeEt != null) {
                    Bundle bundle = data.getExtras();
                    if (bundle != null) {
                        //mImageView.setImageBitmap((Bitmap) data.getParcelableExtra("bitmap"));
                        mCurrenBrandeCodeEt.setText(bundle.getString("result"));
                    }
                }
            }
        }
    }

    private OnProcessListener mOnProcessListener = null;

    public void setOnProcessListener(OnProcessListener l) {
        mOnProcessListener = l;
    }

    public interface OnProcessListener {
        public void onProcessFinish(String stockId);
    }
}
